package com.example.wakaka.locknlock;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

public class IndexActivity extends AppCompatActivity {
    final String testurl = "http://172.18.32.6:3000";
    final String UNLOCKRECORD = "allUnlockingRecord";
    final String WARNING = "WarningRecord";
    final String LOCKSTATE = "LockState";
    final String Unlocking = "Unlocking";


    //final String testurl = "https://space.bilibili.com/ajax/top/showTop?mid=2";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        Button btnUnlock = findViewById(R.id.btnUnlock);
        Button btnRecord = findViewById(R.id.btnRecord);
        Button btnState = findViewById(R.id.btnState);
        Button btnWarn = findViewById(R.id.btnWarn);
        btnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request(3);
            }
        });
        btnUnlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                request(1);
            }
        });
        btnState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request(2);
            }
        });
        btnWarn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request(4);
            }
        });
    }
    OkHttpClient build = new OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.SECONDS)
            .readTimeout(2, TimeUnit.SECONDS)
            .writeTimeout(2, TimeUnit.SECONDS)
            .build();
    public void request(int i)
    {
        /*
        i=1:解锁
        i=2:查询状态
        i=3:查询记录
        i=4:报警记录
         */
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(testurl) // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(build)
                .build();
        GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
        //String text = editText.getText().toString();
        Call<RecycleObj> call = request.getBlog(LOCKSTATE);
        if(i == 1)
        {
            POST_Interface post_interface = retrofit.create(POST_Interface.class);
            call = post_interface.unlock("123456");
        }
        if(i == 2)
        {
            request = retrofit.create(GetRequest_Interface.class);
            call = request.getBlog(LOCKSTATE);
        }
        if(i == 3)
        {
            request = retrofit.create(GetRequest_Interface.class);
            call = request.getBlog(UNLOCKRECORD);
        }
        if(i == 4)
        {
            request = retrofit.create(GetRequest_Interface.class);
            call = request.getBlog(WARNING);
        }


        call.enqueue(new Callback<RecycleObj>() {

            //请求成功时回调
            @Override
            public void onResponse(Call<RecycleObj> call, Response<RecycleObj> response) {
                // 步骤7：处理返回的数据结果：输出翻译的内容

                if(response.body() == null)
                {
                    Toast.makeText(IndexActivity.this,"无此用户",Toast.LENGTH_LONG).show();
                    return;
                }
                else
                {
                    //Toast.makeText(IndexActivity.this,"success",Toast.LENGTH_LONG).show();
                    Toast.makeText(IndexActivity.this,response.body().getMsg(),Toast.LENGTH_LONG).show();
                    //Toast.makeText(IndexActivity.this, "查看记录成功", Toast.LENGTH_LONG).show();
                    if(response.body().getrecord() != null)
                    {
                        Intent intent = new Intent(IndexActivity.this, DetailActivity.class);
                        intent.putExtra("list",(Serializable) response.body().getrecord());
                        startActivityForResult(intent, 1);
                    }

                    return;
                }

            }

            //请求失败时回调
            @Override
            public void onFailure(Call<RecycleObj> call, Throwable throwable) {
                System.out.println("请求失败");
                System.out.println(throwable.getMessage());
            }
        });



    }
    public interface GetRequest_Interface {

        String type = "";
        @GET("api/{type}")
        Call<RecycleObj> getBlog(@Path("type") String type );
        // 访问的API是：https://api.github.com/users/{user}/repos
        // 在发起请求时， {user} 会被替换为方法的第一个参数 user（被@Path注解作用）

    }
    public interface POST_Interface {

        @POST("api/Unlocking")
        Call<RecycleObj> unlock(@Query("password") String pwd);
        // 访问的API是：https://api.github.com/users/{user}/repos
        // 在发起请求时， {user} 会被替换为方法的第一个参数 user（被@Path注解作用）

    }
}
